/*
 *英才会硕信息科技有限公司拥有本软件的版权，拥有本软件版权2025   并保留所有权利。
 *Copyright 2021,YCHS Information&Science Technology Co.,Ltd,
 *All rights reserved.
 */
package com.ychs.lawyerback01.service.imp;

import com.ychs.lawyerback01.mapper.MenuMapper;
import com.ychs.lawyerback01.mapper.UserMapper;
import com.ychs.lawyerback01.pojo.MenuEntity;
import com.ychs.lawyerback01.pojo.UserEntity;
import com.ychs.lawyerback01.service.MenuService;
import com.ychs.lawyerback01.vo.MenuQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @author xuehongjin
 * @version 1.0
 * @date 2025/8/18
 */
@Service
public class MenuServiceImp implements MenuService {
    @Autowired
  private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<MenuQueryVo> getMenusByUserId(Long userId) {
        //先通过UserId找到用户的角色Id
        UserEntity userEntity = userMapper.getUserByUserId(userId);
        //跟据角色id，找到该角色有事吗权限
        List<MenuEntity> menus = menuMapper.getMenusByRoleId(userEntity.getRoleId());
        List<MenuQueryVo> menuQueryVoList = new ArrayList<>();
        //把查询到的菜单封装到树状结构里面
        menus.stream().filter(menu->
            menu.getParentId()==0
        ).sorted(Comparator.comparing(MenuEntity::getOrderNum))
                .forEach(menu->{
                    MenuQueryVo menuQueryVo = new MenuQueryVo();
                    BeanUtils.copyProperties(menu,menuQueryVo);
                    //找当前menu地有权限的子菜单
                    List<MenuQueryVo> subMenus = getChildrenMenus(menus,menuQueryVo);
                    menuQueryVo.setSubMenus(subMenus);
                    menuQueryVoList.add(menuQueryVo);
                });
        return menuQueryVoList;
    }

    private List<MenuQueryVo> getChildrenMenus(List<MenuEntity> menus, MenuQueryVo menuQueryVo) {
        List<MenuQueryVo> list = new ArrayList<>();
        menus.stream().filter(menu->menu.getParentId().equals(menuQueryVo.getMenuId()))
                .sorted(Comparator.comparing(MenuEntity::getOrderNum))
                .forEach(menu->{
                    MenuQueryVo menuQueryVo1 = new MenuQueryVo();
                    BeanUtils.copyProperties(menu,menuQueryVo1);
                    getChildrenMenus(menus,menuQueryVo1);
                    List<MenuQueryVo> childrenMenus = getChildrenMenus(menus,menuQueryVo1);
                    menuQueryVo.setSubMenus(childrenMenus);
                    list.add(menuQueryVo1);
                });
        return list;
    }
    @Override
    public List<MenuEntity> getAllMenus() {
        return menuMapper.selectAll();
    }
}
